<template>
    <el-drawer v-model="drawer" :with-header="false" :append-to-body="true" width="730px" size="85%" :before-close="handleClose">
        <div class="page-container" style="padding: 30px 20px;">
            <el-row justify="space-between">
                <el-col :span="12">
                    <!-- <el-button type="primary" size="small" @click="openCreate">新建线索</el-button>
                    <el-button size="small" @click.stop.prevent="batchEditEvent">批量修改</el-button> -->
                </el-col>
                <el-col :span="12" style="justify-content:flex-end;display:flex;">

                    <!--                <el-button size="small" icon="ele-Refresh" @click.stop.prevent="resetQueryEvent">查看全部客户</el-button>-->
                    <el-button size="small" icon="ele-Refresh" @click.stop.prevent="resetQueryEvent">查看全部</el-button>

                    <el-button size="small" :icon="Upload">导出</el-button>
                    <el-upload v-model:file-list="uploadList" :action="action" :headers="headers" :limit="1"
                        style="margin: 0 12px">
                        <el-button size="small" :icon="Download">导入</el-button>
                    </el-upload>
                    <el-button size="small">17名单</el-button>
                    <el-button size="small" :icon="Filter" @click="openFilter">综合筛选</el-button>
                    <el-button size="small" :icon="Setting" @click="openHeader">表头设置</el-button>
                </el-col>
            </el-row>
            <div class="table-box">
                <el-table :data="list" v-loading="tableLoading" @selection-change="selectionOpportunityEvent" size="small"
                    class="tableList">
                    <el-table-column type="selection" width="30" fixed="left"></el-table-column>
                    <el-table-column v-for="item in header" :key="item.id" :prop="item.fieldName" min-width="100px">
                        <template #header>
                            <span style="margin-right:2px;">{{ item.name }}</span>
                            <!-- 可搜索表头 -->
                            <el-popover placement="bottom" :width="100" trigger="click"
                                v-if="item.isFilter && item.filter == 'search'">
                                <template #reference>
                                    <el-icon :size="15" color="var(--el-color-primary)">
                                        <ele-Search />
                                    </el-icon>
                                </template>
                                <el-input :placeholder="`请输入${item.name}`" v-model.trim="search[item.fieldName]"
                                    size="small" title="按下回车即可搜索" clearable @keydown.enter="searchTable" />
                            </el-popover>
                            <!-- 可筛选表头 -->
                            <el-popover placement="bottom" :width="225" trigger="click" @after-leave="searchTable"
                                v-if="item.isFilter && item.filter == 'filter'">
                                <template #reference>
                                    <el-icon :size="15"
                                        :color="(search[item.fieldName].length > 0) ? 'red' : 'var(--el-color-primary)'">
                                        <ele-Filter />
                                    </el-icon>
                                </template>
                                <!-- 多选框并分页 -->
                                <checkbox-page-list :data="filterList[item.fieldName]" v-model="search[item.fieldName]"
                                    label="id" name="name" />
                            </el-popover>

                            <!--可分页选择表头 v2 -->
                            <el-popover placement="bottom" :width="225" trigger="click" @after-leave="searchTable"
                                v-if="item.isFilter && item.filter == 'select'">
                                <template #reference>
                                    <el-icon :size="15"
                                        :color="(search[item.fieldName].length > 0) ? 'red' : 'var(--el-color-primary)'">
                                        <ele-Filter />
                                    </el-icon>
                                </template>
                                <!-- 多选框并分页 -->
                                <checkbox-page-list v-model="search[item.fieldName]" :server-api="manageUserApi"
                                    name="nickname" label="id" />
                            </el-popover>

                        </template>
                        <!--    可点击的表格  -->
                        <template #default="scope" v-if="item.fieldName === 'nickname'">
                            <span class="primary" @click="openDetail(scope.row)">{{ scope.row.nickname }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <div class="page-block">
                    <el-pagination v-model:currentPage="current" v-model:page-size="page" :total="total"
                        :page-sizes="[10, 20, 30, 40]" :small="true" :disabled="false" :background="false"
                        :size-change="loadTableData" layout="total, sizes, prev, pager, next, jumper"
                        :hide-on-single-page="true" @size-change="loadTableData" @current-change="loadTableData" />
                </div>
            </div>
            <!-- 创建用户 -->
            <customer-create v-model:dialogDrawer="dialogCreate" @onSubmit="createCustomerEvent" />
            <!-- 表头处理 -->
            <table-header v-model:dialogDrawer="dialogHeader" :defaultHeader="header"></table-header>
            <!-- 客户阶段 -->
            <stage-setting v-model:dialogDrawer="dialogStage"></stage-setting>
            <!-- 抽屉客户详情 -->
            <!--  <customer-detail v-model:dialogDrawer="dialogDetail" :defaultForm="rowForm"></customer-detail>-->
            <customer-detail v-model:dialogDrawer="dialogDetail"></customer-detail>
            <!-- 行动统计  -->
            <account-setting v-model:dialogDrawer="dialogAccount" v-model:defaultForm="accountForm"></account-setting>
            <!--  综合搜索   -->
            <table-filter v-model:dialogDrawer="dialogFilter" @getFilter="filterSearch"
                @search="searchEvent"></table-filter>
            <!-- 批量修改  -->
            <customer-batch-edit v-model:dialogPop="dialogBatchEdit" @submit="batchEditSubmitEvent"></customer-batch-edit>
        </div>
    </el-drawer>
</template>
<script>
import { computed, onBeforeMount, onMounted, reactive, toRefs } from 'vue'
import { Download, Upload, Filter, Setting } from '@element-plus/icons-vue'
import CustomerCreate from '../../crm/components/CustomerCreate.vue'
import TableHeader from '../../crm/components/TableHeader.vue'
import StageSetting from '../../crm/components/StageSetting.vue'
import CustomerDetail from '../../crm/components/CustomerDetail.vue'
import AccountSetting from '../../crm/components/AccountSetting.vue'
import TableFilter from '../../crm/components/TableFilter.vue'
import CustomerBatchEdit from "../../crm/components/CustomerBatchEdit.vue";
import { ElMessage } from "element-plus";

import { actionStatisticCache } from "/@/stores/ums/customer/actionStatisticStores.ts";
import { stageStatusCache } from "/@/stores/ums/customer/stageStatusStores";
import { customerTypeCache } from "/@/stores/ums/customer/typeStores";
import { sourceCache } from "/@/stores/ums/customer/sourceStores";
import { productLineCache } from "/@/stores/ums/customer/productLineStores";
import { customerTableHeaderCache } from "/@/stores/ums/customer/customerTableHeaderStores";
import opportunityApi from "/@/api/ums/customer/opportunity";
import { storeToRefs } from "pinia";
import SelectStaff from "../../crm/components/SelectStaff.vue";
import customerDetailStores from "/@/stores/ums/customer/customerDetailStores";
import { businessScopeCache } from "/@/stores/ums/customer/businessScopeStores";
import CheckboxPageList from "../../crm/components/CheckboxPageList.vue";

import { Session } from '/@/utils/storage'
import { getManageUsers } from '/@/api/sys/user';
import api from '/@/api/commonApi'

export default {
    name: 'ThreadList',
    components: {
        CheckboxPageList,
        SelectStaff,
        CustomerBatchEdit,
        CustomerCreate,
        TableHeader,
        StageSetting,
        CustomerDetail,
        AccountSetting,
        TableFilter
    },
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        id: {
            type: String,
            default: null
        }
    },
    setup(props, context) {
        const { dialogDrawer, id } = toRefs(props)
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        // 结构全局缓存
        const { stageStatusList, disuseStatusList, list: stageList, statusListLoading } = storeToRefs(stageStatusCache())
        const { channelList, list: sourceList } = storeToRefs(sourceCache())
        const { tableHeader } = storeToRefs(customerTableHeaderCache())
        const { list: actionStatisticList } = storeToRefs(actionStatisticCache())
        const { list: customerTypeList } = storeToRefs(customerTypeCache())
        const { list: productLineList } = storeToRefs(productLineCache())
        const { detailData } = storeToRefs(customerDetailStores())
        const manageUserApi = getManageUsers
        const state = reactive({
            action: '/api/file/filaAttach/upload',
            headers: {
                '17work': Session.get('token')
            },
            // 计算属性
            status: [],
            dialogBatchEdit: false,// 批量操作
            tableLoading: false,// 表格加载控制
            selectOpportunityIds: [],// 已选中的机会主键
            disuseStatus: [],
            accountData: [
                {
                    name: '昨日',
                    action: 0,
                    view: 1,
                    phone: 2,
                    case: 2
                }, {
                    name: '今日',
                    action: 2117,
                    view: 1,
                    phone: 2,
                    case: 2
                }],
            monthAccount: [
                {
                    name: '合同金额',
                    before: 23000,
                    current: 22000
                }, {
                    name: '回款金额',
                    before: 20000,
                    current: 25000
                }],
            // 客户列表
            list: [],
            // 当前页
            current: 1,
            // 页容
            page: 20,
            // 记录数
            total: 0,
            // 搜索数据
            search: {
                nickname: '',// 客户简称
                name: '',// 客户联系人名称
                phone: '',// 客户联系人手机号
                stageName: [],// 客户阶段
                managerNames: [],// 客户经理
                type: [],// 客户类型
                sourceChannel: [],// 客户来源
                customerList: null,// 客户状态
                teamList: [],// 团队
            },
            manageUsers: [],   // 客户经理列表（管理的用户）
            // 动态表头数据列表
            header: [],
            dialogCreate: false,
            dialogHeader: false,
            dialogStage: false,
            dialogDetail: false,
            rowForm: {},
            // 统计行动列表表头
            accountForm: [],
            dialogAccount: false,
            dialogFilter: false,
            uploadList: [],
            // 过滤下拉列表
            filterList: {
                stageName: [], // 阶段数据
                type: [],// 客户类型
                manage: [],// 客户经理
                managerId: '',// 客户经理
                sourceChannel: [],// 来源
                belong: [],
            },
        })

        // 客户阶段数据监听
        state.status = stageStatusList
        // 客户阶段失效数据
        state.disuseStatus = disuseStatusList
        // 来源渠道
        state.filterList.sourceChannel = channelList
        // 表头数据
        state.header = tableHeader
        // 行动统计表头
        state.accountForm = actionStatisticList
        // 阶段列表
        state.filterList.stageName = stageList
        // 客户类型
        state.filterList.type = customerTypeList

        // 获取数据
        // onBeforeMount(()=>{
        // 行动统计
        // state.accountForm = actionStatisticCache().getList()
        // 阶段数据
        // state.filterList.stageName = stageStatusCache().getList()
        // 客户类型
        // state.filterList.type = customerTypeCache().getList()
        // })

        const openLifeSetting = () => {
            state.dialogStage = true
        }
        const openActionSetting = () => {
            state.dialogAccount = true
        }
        const handleSizeChange = () => {
        }
        const handleCurrentChange = () => {
            console.log(state.current);
        }
        const openDetail = e => {
            state.dialogDetail = false
            customerDetailStores().destroy()
            // 点击时加载点击的这用户的信息
            detailData.value = e
            state.rowForm = e
            state.dialogDetail = true
            customerDetailStores().init()
        }
        // 表头搜索调用
        const searchTable = () => {
            restPage()
            loadTableData()
        }
        const openCreate = () => {
            state.dialogCreate = true
        }
        const openHeader = () => {
            state.dialogHeader = true
        }
        const openFilter = () => {
            state.dialogFilter = true
        }
        const selectionOpportunityEvent = (e) => {
            if (!e) return
            state.selectOpportunityIds = e.map(m => m.id)
        }
        // 综合搜索 - 每勾选一下就会调用
        const filterSearch = e => {
            // eslint-disable-next-line no-console
            // console.log("=>",e)
        }
        // 综合搜索 - 关闭抽屉时调用
        const searchEvent = e => {
            const { teamList, customerList } = e
            state.search.teamList = teamList
            state.search.customerList = customerList
            loadTableData()
        }
        // 显示批量操作对话框
        const batchEditEvent = () => {
            // 检查是否有选中
            if (state.selectOpportunityIds && state.selectOpportunityIds.length > 0)
                return state.dialogBatchEdit = true
            ElMessage.error("至少选中一个客户")
        }
        // 批量操作提交
        const batchEditSubmitEvent = async (e) => {
            if (!e) return
            // 组合对象
            const batchData = {
                // ids:state.selectOpportunityIds.join(','),
                ids: state.selectOpportunityIds,
                ...e
            }
            state.tableLoading = true
            try {
                // 发起异步操作
                const { data } = await opportunityApi.batchEdit(batchData)
                ElMessage.success(data)
                // 刷新列表 & 清空选中
                resetQueryEvent()
                // 刷新客户阶段统计列表
                stageStatusCache().loadList()
            } catch (e) {
                console.log('批量修改异常捕获=>', e);
                ElMessage.error(e.message)
            }
            state.tableLoading = false
        }

        // 检查对象中的字段不为空
        const fieldNotNull = (obj, fieldName) => {
            if (!obj) return false
            return !!obj[fieldName]
        }
        // 针对数组是否有值
        const checkNotNull = (obj, fieldName) => {
            if (!obj) return false
            if (!fieldName) return false
            if (!obj[fieldName]) return false
            return obj[fieldName].length > 0
        }

        // 加载表格数据
        const loadTableData = async () => {
            state.tableLoading = true
            try {
                // 分页数据
                const page = { current: state.current, size: state.page, marketActivityId: id.value }
                // 搜索数据
                if (fieldNotNull(state.search, 'nickname')) {
                    page['nickname'] = state.search['nickname']
                }
                // 手机号
                if (fieldNotNull(state.search, 'phone')) {
                    page['phone'] = state.search.phone
                }
                // 联系人名称
                if (fieldNotNull(state.search, 'name')) {
                    page['name'] = state.search.name
                }
                // 阶段
                if (checkNotNull(state.search, 'stageName')) {
                    page.stageIds = state.search.stageName
                }
                // 客户类型
                if (checkNotNull(state.search, 'type')) {
                    page.customerTypes = state.search.type
                }
                // 客户经理
                if (fieldNotNull(state.search, 'managerNames')) {
                    page['managerIds'] = state.search.managerNames
                }
                // 来源
                if (checkNotNull(state.search, 'sourceChannel')) {
                    page['sourceChannels'] = state.search.sourceChannel
                }
                // 客户状态
                if (state.search.customerList != null) {
                    page['customerStatus'] = state.search.customerList
                }
                console.log(page)
                // 查询数据库
                // const { data } = await umsOpportunityApi().page(page);
                const { data } = await api.marketPage(page);
                const { records, total, size, current } = data
                // 回填数据
                state.list = records.map(l => {
                    // 回填客户阶段
                    l['stageName'] = stageList.value.filter(f => l['stageId'] === f['id'])[0]?.name
                    // 回填客户类型
                    l['type'] = state.filterList.type.filter(f => l['customerType'] === f['id'])[0]?.name
                    // 回填客户来源渠道
                    l['sourceChannel'] = sourceList.value.filter(f => l['sourceChannel'] === f['id'])[0]?.name
                    // 客户来源场景
                    l['scene'] = sourceList.value.filter(f => l['sourceScene'] === f['id'])[0]?.name
                    // 产品线
                    l['productLineName'] = productLineList.value.filter(f => l['productLineId'] === f['id'])[0]?.name
                    // 修改合作该率
                    if (l['probability']) l['probability'] = l['probability'] + '%'
                    // 经营范围中文字
                    l['business'] = businessScopeCache().findById(l['businessScope'])
                    // 金钱格式化 ???
                    return l
                })
                state.total = total
                state.page = size
                state.current = current
            } catch (e) {
                ElMessage.warning(e.message);
            }
            state.tableLoading = false
        }
        // 关闭
        const handleClose = () => {
            context.emit('update:dialogDrawer', false)
        }

        // 生命周期加载表格数据
        onBeforeMount(() => {
            try {
                getManageUsers().then(res => state.manageUsers = res.data)
            } catch (e) {
                console.log(e)
            }
            loadTableData()
        })
        // 创建客户
        const createCustomerEvent = () => {
            stageStatusCache().loadStatusList() // 重新统计一下阶段
            restPage()
            loadTableData()
        }
        const restPage = () => {
            state.list = [];
            state.total = 0;
            state.page = 20;
            state.current = 1;
            state.selectOpportunityIds = [];
        }
        // 清除搜索并重新加载
        const resetQueryEvent = () => {
            restPage()
            state.search = {
                nickname: '',// 客户简称
                name: '',// 客户联系人名称
                phone: '',// 客户联系人手机号
                stageName: [],// 客户阶段
                managerNames: [],// 客户经理
                type: [],// 客户类型
                sourceChannel: [],// 客户来源
                customerList: null,// 客户状态
                teamList: [],// 团队
            }
            // 重新加载表格数据
            loadTableData()
            // 刷新客户阶段统计列表
            stageStatusCache().loadStatusList()
        }

        return {
            ...toRefs(state),
            Download,
            Upload,
            Filter,
            Setting,
            drawer,
            openLifeSetting,
            openActionSetting,
            handleSizeChange,
            handleCurrentChange,
            openDetail,
            searchTable,
            openCreate,
            openHeader,
            StageSetting,
            openFilter,
            filterSearch,
            createCustomerEvent,
            resetQueryEvent,
            loadTableData,
            searchEvent,
            handleClose,
            selectionOpportunityEvent,// 选择表格的勾选
            batchEditEvent,// 批量修改按钮
            batchEditSubmitEvent,// 批量提交事件
            statusListLoading,// 统计数据列表加载状态控制
            manageUserApi
        }
    }
}
</script>
<style scoped lang="scss">
.page-container {
    padding: 1px;

    .page-row {
        display: flex;
        align-items: stretch;
        flex-wrap: wrap;

        .tips-data {
            display: flex;
            align-items: center;
            height: 28px;
            margin-top: 5px;

            .tips {
                margin-right: 3px;
                font-size: 13px;
            }

            &:first-child {
                height: unset;
                margin-top: 0;
            }
        }

        .tips-cell {
            flex: auto;

            .tips-item {
                display: flex;
                align-items: center;
                padding-left: 10px;
                justify-content: space-between;
            }

            .tips-name {
                margin-right: 10px;
                flex: 1;
                overflow: hidden;
                text-align: center;
            }

            .item-data {
                text-align: center;
                height: 28px;
                margin-top: 5px;
                line-height: 28px;
                color: var(--el-menu-text-color);
                font-size: 13px;
            }

            .item-right {
                margin-right: 14px;
            }

            .red {
                color: var(--el-color-danger)
            }

            .green {
                color: var(--el-color-success);
            }
        }

        .divider {
            margin: 5px 10px 0;
            border-right: 1px solid var(--next-border-color-light);
        }

        :deep(.el-table__row) {
            &:last-child {
                .el-table__cell {
                    border-bottom: none;
                }
            }
        }

        :deep(.el-table__inner-wrapper) {
            &::before {
                display: none;
            }
        }
    }

    .tableList {
        border: 1px solid var(--el-table-border-color);
        border-bottom: none;

        :deep(thead .cell) {
            display: flex;
            align-items: center;
        }

        :deep(thead .el-icon) {
            margin-top: -2px;
        }

        .primary {
            cursor: pointer;
            color: var(--el-color-primary);
        }
    }

    .table-box {
        background: #fff;
        margin-top: 10px;

        :deep(.el-table__header-wrapper .el-table__cell) {
            background: var(--el-color-primary-light-9);
            color: var(--next-bg-menuBar-light-1);
        }
    }

    .monthTable {
        :deep(tr) {
            height: 47px;
        }
    }

    .accountTable {
        :deep(tr) {
            height: 43px;
        }
    }
}
</style>
